import os
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
from fastapi import FastAPI, APIRouter
from fastapi import Body
import uvicorn
import fastapi_cdn_host
app=FastAPI()
ApiRouter = APIRouter(prefix="/v1", tags=["api路由"])
file_path= "context.txt"
fastapi_cdn_host.patch_docs(app)
# 允许的源（可以是多个）
origins = [
    "http://127.0.0.1:3000",  # 前端地址
    "http://localhost:3000",
]

# 添加中间件
app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,  # 允许的来源
    allow_credentials=True,  # 允许携带 cookies
    allow_methods=["*"],     # 允许的方法（GET、POST 等）
    allow_headers=["*"],     # 允许的 header
)


@app.get("/")
async def mydb():
    # mydb = mysql.connector.connect(
    #     host="localhost",
    #     user="root",
    #     passwd="123456",
    #     database="djw"
    # )
    # mydbcursor = mydb.cursor()
    # mydbcursor.execute(f"select * from {tabels}")
    # results = mydbcursor.fetchall()
    # mydbcursor.close()
    # mydb.close()
    list=[[
      "95001",
      "王小明",
      "男",
      21
    ],
    [
      "95002",
      "张梅梅",
      "女",
      20
    ],
    [
      "95003",
      "刘小阳",
      "男",
      22
    ]
  ]
    return list

@app.get("/world")
async def world():
    return {"message":"Hello World"}

@app.get("/getlist")
async def getlist():
    contact_List = []
    if os.path.exists(file_path):
        with open(file_path, 'r', encoding='utf-8') as rfile:
            contacts = rfile.readlines()
            for item in contacts:
                contact_List.append(eval(item))

    return contact_List



class InsertBook(BaseModel):
    val: str
    date: str

def save2(list):  ##文件的写入静态方法
    try:
        cont_txt = open(file_path, 'a', encoding='utf-8')
    except:
        cont_txt = open(file_path, 'w', encoding='utf-8')
    for item in list:
        cont_txt.write(str(item) + '\n')
    cont_txt.close()
@app.post("/insertBook")
async def insertBook(data: InsertBook):
    print(data)
    context_list = []
    context = {"value": data.val, "date": data.date}
    context_list.append(context)
    save2(context_list)
    return context_list

@app.get("/deleteBook")
async def deleteBook(value: str, date: str):
    if os.path.exists(file_path):
        with open(file_path, 'r', encoding='utf-8')as file:
            contact_old = file.readlines()
    else:
        contact_old = []
    if contact_old:
        with open(file_path, 'w', encoding='utf-8')as wfile:
            for item in contact_old:
                d = dict(eval(item))
                print(d)
                if d['value'] != value or d['date'] != date:
                    wfile.write(str(d) + '\n')
                    # print(d)
    else:
        return False

if __name__ == '__main__':
    uvicorn.run('2:app',host='0.0.0.0',port=8000,reload=True,workers=4)